
Imports System.Xml
Imports System.IO

Public Class frmImportDrug
    Private objData As New DataAccess
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub frmImportDrug_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            SetImageControl(Me)

            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgMDIForm.Images(22), Bitmap).GetHicon())

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click
        Try
            If Me.txtXMLFileLocation.Text = "" Then
                MessageBox.Show("No directory containing the XML files has been selected.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If

            'get a count of the files to be converted

            Dim FileCount As Integer

            'set the directory
            Dim strXmlDirectory As String
            strXmlDirectory = Me.txtXMLFileLocation.Text

            Directory.SetCurrentDirectory(strXmlDirectory)

            'get XMl files from subdirectories
            For Each Dir As String In Directory.GetDirectories(strXmlDirectory)
                For Each FileName As String In Directory.GetFiles(Dir, "*.xml")
                    FileCount += 1
                Next
            Next

            'get XMl files from selected directories
            For Each FileName As String In Directory.GetFiles(strXmlDirectory, "*.xml")
                FileCount += 1
            Next

            If MessageBox.Show("You will load data from " & FileCount & " Files." & vbCrLf & "This may take a few minutes." & vbCrLf & "Do you wish to carry on?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
                Exit Sub
            End If


            If InsertData(FileCount) = True Then
                MessageBox.Show("Data imported successfully.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Function InsertData(ByVal FileCount As Integer) As Boolean

        'set the directory
        Dim strXmlDirectory As String
        strXmlDirectory = Me.txtXMLFileLocation.Text

        Directory.SetCurrentDirectory(strXmlDirectory)

        Dim objNodeList As XmlNodeList
        Dim objNode, MainNode As XmlNode
        Dim objChildNode As XmlNode
        Dim objChildNodeList As XmlNodeList
        Dim objXMLDom As New XmlDocument
        Dim intSuccess As Integer

        Dim strDrugname As String = ""
        Dim strDrugCategory As String = ""
        Dim strTherapeuticClass As String = ""
        Dim strPharmacyClass As String = ""
        Dim intDrugID As Integer


        'DirArray contains selected directory and subdirectories within it
        Dim DirArray As String()
        DirArray = Directory.GetDirectories(strXmlDirectory) 'this will give only subdirectories 
        'Add the selected directory path  to array
        ReDim Preserve DirArray(DirArray.Length)
        DirArray(DirArray.Length - 1) = strXmlDirectory
        Dim i As Integer

        Try
            For Each Dir As String In DirArray
                For Each FileName As String In Directory.GetFiles(Dir)
                    objXMLDom.Load(FileName)
                    MainNode = objXMLDom.SelectSingleNode("//monograph")
                    If Not MainNode Is Nothing Then
                        If MainNode.Attributes("herbal").Value = "yes" Then
                            strDrugCategory = "Herb"
                        Else
                            strDrugCategory = "Drug"
                        End If

                        strDrugname = MainNode.Attributes("id").Value

                        'Now capilatise the initial letter
                        strDrugname = strDrugname.Substring(0, 1).ToUpper & strDrugname.Substring(1)

                        'get the classifications
                        objNode = objXMLDom.SelectSingleNode("//thera.classification")

                        If Not objNode Is Nothing Then
                            For i = 0 To objNode.ChildNodes.Count - 1
                                If objNode.ChildNodes(i).NodeType = XmlNodeType.Element Then
                                    strTherapeuticClass = objNode.ChildNodes(i).Name
                                End If
                            Next
                        Else
                            strTherapeuticClass = String.Empty
                        End If

                        objNode = objXMLDom.SelectSingleNode("//pharm.classification")
                        If Not objNode Is Nothing Then
                            strPharmacyClass = objNode.ChildNodes(0).Name
                        Else
                            strPharmacyClass = String.Empty
                        End If


                        'insert into drugs table
                        intDrugID = InsertDrug(strDrugname, strDrugCategory, strTherapeuticClass, strPharmacyClass, True)

                        If intDrugID = 0 Then
                            MessageBox.Show("Unable to insert entry for " & objNode.InnerText, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Function
                        End If


                        If intDrugID <> -1 Then
                            If strDrugCategory = "Drug" Then
                                objNodeList = objXMLDom.SelectSingleNode("//indications").ChildNodes
                                If objNodeList.Count <> 0 Then
                                    DeleteFromTable("tblDrugIndications", intDrugID)
                                    For Each objNode In objNodeList
                                        If objNode.Name = "main.entry" Then
                                            intSuccess = InsertDrugIndication(intDrugID, objNode.InnerText)
                                            If intSuccess = 0 Then
                                                MessageBox.Show("Unable to insert indications entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                                Exit Function
                                            End If
                                        End If
                                    Next
                                End If
                            Else
                                objNodeList = objXMLDom.SelectSingleNode("//common.uses").ChildNodes
                                If objNodeList.Count <> 0 Then
                                    DeleteFromTable("tblDrugIndications", intDrugID)
                                    For Each objNode In objNodeList
                                        If objNode.Name = "main.entry" Then
                                            intSuccess = InsertDrugIndication(intDrugID, objNode.InnerText)
                                            If intSuccess = 0 Then
                                                MessageBox.Show("Unable to insert indications entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                                Exit Function
                                            End If
                                        End If
                                    Next
                                End If
                            End If

                            'Drug action as before
                            objNodeList = objXMLDom.SelectSingleNode("//drug.action").ChildNodes
                            If objNodeList.Count <> 0 Then
                                DeleteFromTable("tblDrugActions", intDrugID)
                                For Each objNode In objNodeList
                                    If objNode.Name = "main.entry" Then
                                        intSuccess = InsertDrugAction(intDrugID, objNode.InnerText)
                                        If intSuccess = 0 Then
                                            MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                            Exit Function
                                        End If
                                    End If
                                Next
                            End If

                            'Contraindications
                            objNodeList = objXMLDom.SelectSingleNode("//contraindicated").ChildNodes
                            If objNodeList.Count <> 0 Then
                                DeleteFromTable("tblDrugContraIndicator", intDrugID)
                                For Each objNode In objNodeList
                                    If objNode.Name = "main.entry" Then
                                        intSuccess = InsertDrugContraIndicator(intDrugID, objNode.InnerText)
                                        If intSuccess = 0 Then
                                            MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                            Exit Function
                                        End If
                                    End If
                                Next
                            End If

                            'cautions
                            objNodeList = objXMLDom.SelectSingleNode("//drug.caution").ChildNodes
                            If objNodeList.Count <> 0 Then
                                DeleteFromTable("tblDrugCaution", intDrugID)
                                For Each objNode In objNodeList
                                    If objNode.Name = "main.entry" Then
                                        intSuccess = InsertDrugCaution(intDrugID, objNode.InnerText)
                                        If intSuccess = 0 Then
                                            MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                            Exit Function
                                        End If
                                    End If
                                Next
                            End If

                            'Theraputic effects
                            objNodeList = objXMLDom.SelectSingleNode("//therapeutic.effects").ChildNodes
                            If objNodeList.Count <> 0 Then
                                DeleteFromTable("tblDrugTheraputics", intDrugID)
                                For Each objNode In objNodeList
                                    If objNode.Name = "main.entry" Then
                                        intSuccess = InsertDrugTheraputic(intDrugID, objNode.InnerText)
                                        If intSuccess = 0 Then
                                            MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                            Exit Function
                                        End If
                                    End If
                                Next
                            End If


                            Dim strEffect As String
                            Dim strArea As String
                            Dim strSignificance As String

                            objNode = objXMLDom.SelectSingleNode("//adverse.reaction.section")
                            For i = 0 To objNode.ChildNodes.Count - 1
                                If objNode.ChildNodes(i).Name = "body.syslist" Then
                                    objNodeList = objNode.ChildNodes(i).ChildNodes
                                    Exit For
                                End If
                            Next

                            If objNodeList.Count <> 0 Then
                                DeleteFromTable("tblDrugSideEffects", intDrugID)
                                For Each objNode In objNodeList
                                    strArea = objNode.Name
                                    objChildNodeList = objNode.ChildNodes
                                    For Each objChildNode In objChildNodeList
                                        If objChildNode.NodeType = XmlNodeType.Element Then
                                            strEffect = objChildNode.InnerText
                                            If objChildNode.Attributes("signif") Is Nothing Then
                                                strSignificance = ""
                                            Else
                                                strSignificance = objChildNode.Attributes("signif").Value
                                            End If


                                            intSuccess = InsertDrugSideEffect(intDrugID, strEffect, strArea, strSignificance)
                                            If intSuccess = 0 Then
                                                MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                                Exit Function
                                            End If
                                        End If
                                    Next
                                Next
                            End If

                            'Dosage
                            If strDrugCategory = "Drug" Then
                                objNodeList = objXMLDom.SelectSingleNode("//route.dosage.section").ChildNodes
                                Dim strDose As String = ""
                                Dim strAdultChild As String = ""
                                Dim strRoute As String = ""
                                Dim strAgeWeight As String = ""
                                Dim j As Integer

                                If objNodeList.Count <> 0 Then
                                    DeleteFromTable("tblDrugDosage", intDrugID)
                                    For Each objNode In objNodeList
                                        strRoute = ""
                                        If objNode.Name = "route" Then

                                            For i = 0 To objNode.ChildNodes.Count - 1
                                                If objNode.ChildNodes(i).Name = "dosage" Then
                                                    strDose = objNode.ChildNodes(i).InnerText
                                                    Exit For
                                                End If
                                            Next

                                            'the age weight will be the nde preceeding the dose
                                            strAgeWeight = objNode.ChildNodes(i - 1).InnerText
                                            'the age group will be the one before that
                                            strAdultChild = objNode.ChildNodes(i - 2).Name
                                            'the remainder will be the route of administration
                                            For j = 0 To i - 3
                                                strRoute &= objNode.ChildNodes(j).Name & " or "
                                            Next
                                            strRoute = strRoute.Substring(0, Len(strRoute) - 3)
                                            intSuccess = InsertDrugDose(intDrugID, strDose, strAdultChild, strRoute, strAgeWeight)
                                            If intSuccess = 0 Then
                                                MessageBox.Show("Unable to insert actions entry for " & strDrugname, "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
                                                Exit Function
                                            End If
                                        End If
                                    Next
                                End If
                            Else 'we have some herbs
                                objNodeList = objXMLDom.SelectSingleNode("//route.commonly.used.dosage.section").ChildNodes
                                Dim strDose As String = ""
                                Dim strAdultChild As String = ""
                                Dim strRoute As String = ""
                                Dim strAgeWeight As String = ""
                                Dim j As Integer

                                If objNodeList.Count <> 0 Then
                                    DeleteFromTable("tblDrugDosage", intDrugID)
                                    For Each objNode In objNodeList
                                        strRoute = ""
                                        If objNode.Name = "route" Then

                                            For i = 0 To objNode.ChildNodes.Count - 1
                                                If objNode.ChildNodes(i).Name = "dosage" Then
                                                    strDose = objNode.ChildNodes(i).InnerText
                                                    Exit For
                                                End If
                                            Next

                                            'the age weight will be the nde preceeding the dose
                                            strAgeWeight = objNode.ChildNodes(i - 1).InnerText
                                            'the age group will be the one before that
                                            strAdultChild = objNode.ChildNodes(i - 2).Name
                                            'the remainder will be the route of administration
                                            For j = 0 To i - 3
                                                strRoute &= objNode.ChildNodes(j).Name & " or "
                                            Next
                                            strRoute = strRoute.Substring(0, Len(strRoute) - 3)
                                            intSuccess = InsertDrugDose(intDrugID, strDose, strAdultChild, strRoute, strAgeWeight)
                                            If intSuccess = 0 Then
                                                MessageBox.Show("Unable to insert actions entry for " & strDrugname, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
                                                Exit Function
                                            End If
                                        End If
                                    Next
                                End If
                            End If

                        End If
                    End If 'if statement checking if node is not null
                Next
            Next
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try
        Return True
    End Function

    Private Function InsertDrug(ByVal strDrugName As String, ByVal strDrugCategory As String, ByVal strTherapeuticClass As String, ByVal strPharamcyClass As String, ByVal BlnIsImported As Boolean) As Integer

        Try
            Return objData.InsertDrug(strDrugName, strDrugCategory, strTherapeuticClass, strPharamcyClass, BlnIsImported)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugIndication(ByVal intDrugID As Integer, ByVal strNodeText As String)
        Try
            Return objData.InsertDrugIndication(intDrugID, strNodeText)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugAction(ByVal intDrugID As Integer, ByVal strNodeText As String)
        Try
            Return objData.InsertDrugAction(intDrugID, strNodeText)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugContraIndicator(ByVal intDrugID As Integer, ByVal strNodeText As String)
        Try
            Return objData.InsertDrugContraIndications(intDrugID, strNodeText)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugCaution(ByVal intDrugID As Integer, ByVal strNodeText As String)
        Try
            Return objData.InsertDrugCaution(intDrugID, strNodeText)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugTheraputic(ByVal intDrugID As Integer, ByVal strNodeText As String)
        Try
            Return objData.InsertDrugTheraputicEffect(intDrugID, strNodeText)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugSideEffect(ByVal intDrugID As Integer, ByVal strEffect As String, ByVal strArea As String, ByVal strSignificance As String)
        Try
            Return objData.InsertDrugSideEffect(intDrugID, strEffect, strArea, strSignificance)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Function InsertDrugDose(ByVal intDrugID As Integer, ByVal strDose As String, ByVal strAdultChild As String, ByVal strRoute As String, ByVal strAgeWeight As String) As Integer
        Try
            Return objData.InsertDrugDose(intDrugID, strDose, strAdultChild, strRoute, strAgeWeight)
        Catch ex As Exception
            MessageBox.Show(ex.Message & vbCrLf & "Contact your system administrator", "An Exception Has Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return 0
        End Try
    End Function

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        Dim BrowseFolderDialog As New FolderBrowserDialog
        BrowseFolderDialog.RootFolder = Environment.SpecialFolder.MyComputer

        If BrowseFolderDialog.ShowDialog <> DialogResult.Cancel Then
            txtXMLFileLocation.Text = BrowseFolderDialog.SelectedPath
        End If
    End Sub
End Class